package internal

import (
	"github.com/gin-gonic/gin"
	"inspector/internal/controller/v1/event"
	"inspector/internal/controller/v1/oauth"
	"inspector/internal/dao/mysql"
	"inspector/internal/middleware"
	"inspector/pkg/code"
	"inspector/pkg/errors"
	"inspector/pkg/result"
)

func InitRouter(g *gin.Engine) {
	installController(g)
}

func installController(g *gin.Engine) {
	InstallMiddlewares(g)
	factory, _ := mysql.InitDB()
	g.NoRoute(func(c *gin.Context) {
		result.SendResponse(c, nil, errors.New(code.NewErrPageNotFound(), "Page not found."))
	})
	oauthController := oauth.NewOAuthController(factory)
	oauthGroup := g.Group("/oauth/v1")
	{
		oauthGroup.GET("/callback", oauthController.Callback)
		oauthGroup.POST("/token", middleware.ValidateAtomGitAPIKey(), oauthController.GetToken)
	}
	eventController := event.NewEventController(factory)
	eventGroup := g.Group("/event/v1")
	{
		eventGroup.POST("/webhook", middleware.WebhookCheck(), eventController.Webhook)
	}
}

// InstallMiddlewares install generic middlewares.
func InstallMiddlewares(engine *gin.Engine) {
	// necessary middlewares
	engine.Use(middleware.RequestID())
	engine.Use(middleware.ErrorHandler())
	for _, v := range middleware.Middlewares {
		engine.Use(v)
	}
}
